/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * email:nur01@qq.com
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, Image, ListView, RefreshControl, StyleSheet, Text, View} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import DateTimePicker from 'react-native-modal-datetime-picker'
import moment from 'moment'
import ActivateTowPage from "./ActivateTowPage";
import I18n from '../../../res/language/i18n'
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import IparInput from "../../../custom/IparInput";
import AlertDialog from "../../../custom/AlertDialog";
import LoginPage from "../LoginPage";
import CommonUtils from "../../../common/CommonUtils";
import CustomerServicePage from "../CustomerServicePage";
import IparImageView from "../../../custom/IparImageView";
import ImagePicker from 'react-native-image-picker';

const photoOptions = {
    //底部弹出框选项
    cancelButtonTitle: I18n.t('default.cancel'),
    takePhotoButtonTitle: I18n.t('default.camera'),
    chooseFromLibraryButtonTitle: I18n.t('default.photo'),
    quality: 0.72,
    allowsEditing: true,
    maxWidth: 500,
    noData: false,
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};
export default class ActivateOnePage extends Component {


    constructor(props) {
        super(props);
        this.iparId = '';
        this._iparId = '';

        this.countryData = this.props.countryData || [];
        this.yourName = '';
        this.passPortNumber = '';
        this.taxId = '';
        this.iparNetwork = new IparNetwork();
        this.state = {
            isDateTimePickerVisible: false,
            loading: false,
            alertVisible: false,
            userStatus: 0,
            userData: null,
            yourName: '',
            userBirthday: I18n.t('default.dateOfBirth'),
            userPassportUrl: null,
        }

    }


    componentDidMount() {
        if (this.countryData.length <= 0) {
            this.getCountryData();//获取各位国家的数据
        }
    }


    /**
     * 获取各位国家的数据
     */
    getCountryData() {
        CommonUtils.showLoading();
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', '')
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result && result.length >= 0) {
                    this.countryData = result;
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ActivateOnePage/--getCountryData/-error-', error);
            })
    }

    /**
     * DateTimePicker
     * */
    _showDateTimePicker = () => this.setState({
        isDateTimePickerVisible: true,
    });
    _hideDateTimePicker = () => this.setState({isDateTimePickerVisible: false});
    _handleDatePicked = (date) => {
        let dateFormat = moment(date).format("YYYY-MM-DD");
        this.setState({
            userBirthday: dateFormat,
            isDateTimePickerVisible: false
        });

    };

    startNex() {

        if (!this.iparId.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.iparId'));
            return;
        }
        if (!this.userData) {
            DeviceEventEmitter.emit('toast', I18n.t('default.check'));
            return;
        }
        if (this.iparId !== this._iparId) {
            DeviceEventEmitter.emit('toast', I18n.t('default.check'));
            return;
        }

        if (!this.yourName) {
            DeviceEventEmitter.emit('toast', I18n.t('default.yourName'));
            return;
        }
        if (!this.passPortNumber) {
            DeviceEventEmitter.emit('toast', I18n.t('default.passPortNumber'));
            return;
        }
        if (!this.taxId) {
            DeviceEventEmitter.emit('toast', I18n.t('default.taxId'));
            return;
        }
        if (this.state.userBirthday === I18n.t('default.dateOfBirth')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.dateOfBirth'));
            return;
        }
        if (!this.state.userPassportUrl) {
            DeviceEventEmitter.emit('toast', I18n.t('default.uploadPassPortPhoto'));
            return;
        }

        console.log(JSON.stringify({
            "userData": this.userData,
            "nickName": this.yourName,
            "id_number": this.passPortNumber,
            "birth_day": this.state.userBirthday,
            "personal_tax": this.taxId,
        }));

        this.props.navigator.push({
            component: ActivateTowPage,
            name: 'ActivateTowPage',
            params: {
                userNewInfo: {
                    "userData": this.userData,
                    "nickName": this.yourName,
                    "id_number": this.passPortNumber,
                    "birth_day": this.state.userBirthday,
                    "personal_tax": this.taxId,
                    "passportImage": this.state.userPassportUrl+',',
                },
                "countryData": this.countryData,
                comeFromMePage: this.props.comeFromMePage

            },
        })


    }


    /**
     * 查找用户
     * */
    check() {
        if (!this.iparId.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.iparId'));
            return;
        }
        this.setState({
            loading: true,
        });
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'searchOldUser?', 'keywords=' + this.iparId)
            .then((result) => {
                let resultData = result.data;
                if (result.code === 200 && resultData.status > 0) {//用户已存在
                    this.setState({
                        loading: false,
                        userStatus: resultData.status,
                        userData: resultData,
                        alertVisible: true,
                    });
                    // if (resultData.status === 4 && resultData.status === 6) {
                    //     DeviceEventEmitter.emit('toast', I18n.t('default.activated'));
                    //     this.setState({
                    //         loading: false,
                    //     })
                    // } else {
                    // this._iparId = this.iparId;
                    // let data = resultData;
                    // this.userData = data;
                    // this.yourName = data.nick_name;
                    // this.setState({
                    //     yourName: data.nick_name,
                    //     loading: false,
                    // })
                    // }
                } else {//用户未存在
                    this.setState({
                        loading: false,
                    });
                    DeviceEventEmitter.emit('toast', I18n.t('default.userNotExist'))
                }
            })
            .catch((error) => {
                this.setState({
                    loading: false,
                });
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });

    }

    render() {

        let alertMsj = '';
        switch (this.state.userStatus) {
            case 1:
                alertMsj = I18n.t('a.status1');
                break;
            case 2:
                alertMsj = I18n.t('a.status2');
                break;
            case 3:
                alertMsj = I18n.t('a.status3');
                break;
            case 4:
                alertMsj = I18n.t('a.status4');
                break;
            case 5:
                alertMsj = I18n.t('a.status5');
                break;
            case 6:
                alertMsj = I18n.t('a.status6');
                break;
        }

        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => this.props.navigator.pop()}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />

                <KeyboardAwareScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.loading}
                            onRefresh={() => {
                            }}
                        />
                    }
                >
                    <View style={{padding: 16}}>

                        {/*title*/}
                        {ViewUtils.getTitleView(I18n.t('default.activateAccount'), I18n.t('default.iparDiscountCard'))}


                        <View style={StyleUtils.justifySpace}>
                            <IparInput
                                style={{width: '70%'}}
                                onChangeText={(text) => this.iparId = text}
                                placeholder={I18n.t('default.iparId')}/>
                            {ViewUtils.getButton(I18n.t('default.check'), () => this.check(), [StyleUtils.marginTop, {width: '30%'}])}
                        </View>

                        <IparInput
                            defaultValue={this.yourName}
                            onChangeText={(text) => this.yourName = text}
                            placeholder={I18n.t('default.yourName')}/>

                        <IparInput
                            onChangeText={(text) => this.passPortNumber = text}
                            placeholder={I18n.t('default.passPortNumber')}/>

                        <IparInput
                            onChangeText={(text) => this.taxId = text}
                            placeholder={I18n.t('default.taxId')}/>


                        {ViewUtils.getButtunMenu(this.state.userBirthday, this._showDateTimePicker, StyleUtils.marginTop)}

                        {ViewUtils.getButtunMenu(I18n.t('default.uploadPassPortPhoto'), () => this.cameraAction(), StyleUtils.marginTop)}


                        {this.state.userPassportUrl && <IparImageView
                            style={{marginTop: 16, marginBottom: 16}}
                            url={this.state.userPassportUrl}
                            width={'100%'}
                            resizeMode={'cover'}
                            height={160}
                        />}

                        {ViewUtils.getButton(I18n.t('default.next'), () => this.startNex(), [{marginBottom: 40}, StyleUtils.marginTop])}
                    </View>

                </KeyboardAwareScrollView>


                <AlertDialog
                    requestClose={() => {
                        this.setState({
                            alertVisible: false,
                        })
                    }}
                    visible={this.state.alertVisible}
                    contentTv={alertMsj}
                    centerSts={'OK'}
                    singleBtnOnclick={() => {
                        let data = this.state.userData;
                        switch (this.state.userStatus) {
                            case 5:
                                if (data) {
                                    this._iparId = this.iparId;
                                    this.userData = data;
                                    this.yourName = data.first_name;
                                }
                                break;
                            case 1:
                                this.props.navigator.push({
                                    component: CustomerServicePage,
                                    name: "CustomerServicePage",
                                });
                                break;
                            default: {
                                new CommonUtils().popToRoute(this, 'LoginPage')
                            }

                        }
                        this.setState({
                            alertVisible: false,
                        });
                    }}/>

                {/**
                 * DateTimePicker
                 */}
                <DateTimePicker
                    isVisible={this.state.isDateTimePickerVisible}
                    titleIOS={I18n.t('default.dateOfBirth')}
                    onConfirm={this._handleDatePicked}
                    onCancel={this._hideDateTimePicker}
                />


            </View>
        );
    }


    /**
     * 打开相机
     * */
    cameraAction() {
        if (!this.userData) {
            DeviceEventEmitter.emit('toast', I18n.t('default.check'));
            return;
        }

        ImagePicker.showImagePicker(photoOptions, (response) => {
            if (response.didCancel) {
                console.log('User cancelled image picker');
            } else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            } else {

                CommonUtils.showLoading();
                let formData = new FormData();
                formData.append("prefix", this.userData.rand_id);
                formData.append("file", 'data:image/jpeg;base64,' + response.data);
                formData.append("dir", "user");
                this.iparNetwork.getPostFrom(SERVER_TYPE.imgIpar + 'UploadFile?', formData)
                    .then((result) => {
                        if (result.code === 200 && result.data) {
                            this.setState({
                                userPassportUrl: result.data.url,
                            });
                            DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                            console.log(result);
                        } else {
                            DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                        }
                        CommonUtils.dismissLoading();

                    })
                    .catch((error) => {
                        CommonUtils.dismissLoading();
                        console.log(error);
                        DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    })
            }
        });
    }
}




